import { defineStore } from 'pinia';
import axios from 'axios';

export const characterStore = defineStore('character', {
  state: () => ({
    characters: [],
    character: null,
    categories: [],
    loading: false,
    error: null,
    searchQuery: '',
    currentCategory: '',
    pagination: {
      currentPage: 1,
      totalPages: 1,
      itemsPerPage: 10
    }
  }),

  actions: {
    // 获取角色列表
    async getCharacters(page = 1, itemsPerPage = 10) {
      this.loading = true;
      this.error = null;
      try {
        const params = {
          page,
          itemsPerPage
        };
        
        if (this.searchQuery) {
          params.query = this.searchQuery;
        }
        
        if (this.currentCategory) {
          params.category = this.currentCategory;
        }
        
        const response = await axios.get('/api/characters', { params });
        this.characters = response.data.characters;
        this.pagination = response.data.pagination;
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '获取角色列表失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取单个角色详情
    async getCharacterById(id) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.get(`/api/characters/${id}`);
        this.character = response.data;
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '获取角色详情失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取角色分类
    async getCharacterCategories() {
      try {
        const response = await axios.get('/api/characters/categories');
        this.categories = response.data;
        return response.data;
      } catch (error) {
        console.error('获取角色分类失败:', error);
        return [];
      }
    },

    // 搜索角色
    setSearchQuery(query) {
      this.searchQuery = query;
      this.pagination.currentPage = 1;
      this.getCharacters();
    },

    // 按分类筛选
    setCurrentCategory(category) {
      this.currentCategory = category;
      this.pagination.currentPage = 1;
      this.getCharacters();
    },

    // 创建新角色（管理员）
    async createCharacter(characterData) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.post('/characters', characterData);
        await this.getCharacters(); // 刷新角色列表
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '创建角色失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新角色（管理员）
    async updateCharacter(id, characterData) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.put(`/characters/${id}`, characterData);
        await this.getCharacters(); // 刷新角色列表
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '更新角色失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 删除角色（管理员）
    async deleteCharacter(id) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.delete(`/characters/${id}`);
        await this.getCharacters(); // 刷新角色列表
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '删除角色失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 清除错误信息
    clearError() {
      this.error = null;
    }
  },

  getters: {
    // 获取筛选后的角色列表
    filteredCharacters: (state) => {
      if (!state.searchQuery && !state.currentCategory) {
        return state.characters;
      }
      
      return state.characters.filter(character => {
        const matchesQuery = state.searchQuery 
          ? character.name.toLowerCase().includes(state.searchQuery.toLowerCase()) ||
            character.description.toLowerCase().includes(state.searchQuery.toLowerCase())
          : true;
        
        const matchesCategory = state.currentCategory
          ? character.categories.includes(state.currentCategory)
          : true;
        
        return matchesQuery && matchesCategory;
      });
    }
  }
});